﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using FH.Application.UserApp;
using System.Collections.Specialized;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using WebSite.Models;
using FH.Core.Convert;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using FH.Data;

// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace WebSite.Controllers
{
    public class LoginController : Controller
    {
        private IUserAppService _userAppService;
        private readonly IHttpContextAccessor _httpContextAccessor;
        public LoginController(IUserAppService userAppService
            , IHttpContextAccessor httpContextAccessor)
        {
            _userAppService = userAppService;
            _httpContextAccessor = httpContextAccessor;
        }
        // GET: /<controller>/
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Index(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                //检查用户信息
                var user = _userAppService.CheckUser(model.UserName, model.Password);
                if (user != null)
                {
                    //记录Session
                    var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, model.UserName),
                    new Claim(ClaimTypes.Role, "AccountUser"),
                };

                    var claimsIdentity = new ClaimsIdentity(
                        claims, FHCookieAuthenticationDefaults.AuthenticationScheme);

                    var authProperties = new AuthenticationProperties
                    {
                        ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(30),
                        AllowRefresh = true,
                        IssuedUtc = DateTime.UtcNow,
                        IsPersistent = false,
                    };
                    await _httpContextAccessor.HttpContext.SignInAsync(
                           FHCookieAuthenticationDefaults.AuthenticationScheme,
                           new ClaimsPrincipal(claimsIdentity),
                           authProperties);
                    //跳转到系统首页
                    return RedirectToAction("Index", "Admin");
                }
                ViewBag.ErrorInfo = "用户名或密码错误。";
                return View();
            }
            foreach (var item in ModelState.Values)
            {
                if (item.Errors.Count > 0)
                {
                    ViewBag.ErrorInfo = item.Errors[0].ErrorMessage;
                    break;
                }
            }
            return View(model);
        }
    }
}
